package com.goldcn.sys.service;

import com.goldcn.Interceptor.CurrentUser;
import com.goldcn.common.BaseCode;
import com.goldcn.common.CommonUtils;
import com.goldcn.common.ResultData;
import com.goldcn.common.util.IdGen;
import com.goldcn.sys.dao.GcnSysPageMapper;
import com.goldcn.sys.dao.GcnSysRolePageFunctionMapper;
import com.goldcn.sys.model.GcnSysPage;
import com.goldcn.sys.model.util.Menu;
import org.apache.ibatis.javassist.runtime.Inner;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Component
public class SysPageService {
    @Autowired
    GcnSysPageMapper gcnSysPageMapper;
    @Autowired
    GcnSysRolePageFunctionMapper gcnSysRolePageFunctionMapper;

    //子节点
    static  List<GcnSysPage> childNodes=new ArrayList<GcnSysPage>();

    @Transactional
    public void saveAll(Collection<GcnSysPage> sysPages) {
        for (GcnSysPage sysPage : sysPages) {
            if (sysPage.getPageID() != null && sysPage.getPageID() != "") {
                gcnSysPageMapper.updateByPrimaryKeySelective(sysPage);
            } else {
                sysPage.setPageID(UUID.randomUUID().toString().toUpperCase());
                gcnSysPageMapper.insertSelective(sysPage);
            }
        }
    }

    @Transactional
    public void deleteByID(Collection<GcnSysPage> sysPages) {
        for (GcnSysPage sysPage : sysPages) {
            gcnSysPageMapper.deleteByPrimaryKey(sysPage.getPageID());
        }
    }

    /**
     * 查询角色菜单
     *
     * @param roles
     * @return
     */
    public List<Menu> allMenus(List<String> roles) {
        List<Menu> menus = new ArrayList();
        List<String> rolePages = gcnSysRolePageFunctionMapper.findRolePage(roles);
        Map<String, Object> params = new HashMap();
        params.put("rolePages", rolePages);
        List<GcnSysPage> firstLevelMenus = gcnSysPageMapper.queryTopInPages(params);
        for (GcnSysPage firstLevelMenu : firstLevelMenus) {
            Menu menu = new Menu();
            menu.setParentSysPage(firstLevelMenu);//设置一级菜单

            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("rolePages", rolePages);
            params2.put("parentID", firstLevelMenu.getPageID());
            List<GcnSysPage> secondLevelMenus = gcnSysPageMapper.queryChildrenInPages(params2);

            List<Menu> childrenMenus = new ArrayList<Menu>();
            for (GcnSysPage secondLevelMenu : secondLevelMenus) {
                Menu subMenu = new Menu();
                subMenu.setParentSysPage(secondLevelMenu);
                Map<String, Object> params3 = new HashMap<String, Object>();
                params3.put("rolePages", rolePages);
                params3.put("parentID", secondLevelMenu.getPageID());
                List<GcnSysPage> thirdLevelMenus = gcnSysPageMapper.queryChildrenInPages(params3);
                subMenu.setChildrenSysPages(thirdLevelMenus);
                childrenMenus.add(subMenu);
            }
            menu.setChildrenMenus(childrenMenus);
            menus.add(menu);
        }
        return menus;
    }

    public Map selectAll(Map<String, String> map, CurrentUser user){
        String conditon = "";
        if(CommonUtils.isNotEmpty(map.get("pageName"))){
            conditon += " AND pageName = '" + map.get("pageName") + "'";
        }
        if(CommonUtils.isNotEmpty(map.get("state")) && !"0".equals(map.get("state"))){
            conditon += " AND isStop =  '" + map.get("state") + "'";
        }
        List<GcnSysPage> list = gcnSysPageMapper.selectAll(conditon);
        HashMap result = new HashMap();
        result.put("data", list);
        return result;
    }

    public ResultData getAll(Map<String, String> map){
        ResultData result = new ResultData();
        String conditon = "";
        conditon += " AND isStop != 2 ORDER BY orderBy";
        List<GcnSysPage> list = gcnSysPageMapper.selectAll(conditon);
        result.setData(list);
        return result;
    }


    public ResultData saveOrUpdate(Map<String, String> map, CurrentUser user) throws  Exception{
        ResultData result = new ResultData();
        //判定id，决定是否为修改操作
        String pageID = CommonUtils.isNotEmpty(map.get("pageID")) ? map.get("pageID") : String.valueOf(IdGen.get().nextId());
        boolean opt = CommonUtils.isEmpty(map.get("pageID")) ? true : false;
        GcnSysPage o = null;
        int suc_item = 0;
        if(opt){
            o = new GcnSysPage();
            o.setPageID(pageID);
            o.setPageName(map.get("pageName"));
            o.setPageUrl(map.get("pageUrl"));
            o.setIconUrl(map.get("iconUrl"));
            o.setOrderBy(Strings.isBlank(map.get("orderBy"))?0: Integer.valueOf(map.get("orderBy")));
            o.setParentID(CommonUtils.isEmpty(map.get("parentID")) || "-1".equals(map.get("parentID")) ? null : map.get("parentID"));
            o.setIsStop(0);
            o.setAddUser(user.getUserID());
            o.setAddTime(System.currentTimeMillis());
        }else{
            o = gcnSysPageMapper.selectByPrimaryKey(pageID);
            o.setPageName(map.get("pageName"));
            o.setPageUrl(map.get("pageUrl"));
            o.setIconUrl(map.get("iconUrl"));
            o.setParentID(CommonUtils.isEmpty(map.get("parentID")) || "-1".equals(map.get("parentID")) ? null : map.get("parentID"));
            o.setOrderBy(Strings.isBlank(map.get("orderBy"))?0: Integer.valueOf(map.get("orderBy")));
            o.setUpdateUser(user.getUserID());
            o.setUpdateTime(System.currentTimeMillis());
        }
        suc_item = opt==true ? gcnSysPageMapper.insert(o) : gcnSysPageMapper.updateByPrimaryKey(o);
        return new ResultData(suc_item > 0 ? BaseCode.SUCCESS_CODE : BaseCode.ERROR_CODE, suc_item);
    }

    public ResultData getPage(String id){
        ResultData result = new ResultData();
        GcnSysPage o = gcnSysPageMapper.selectByPrimaryKey(id);
        if(o == null){
            return new ResultData(BaseCode.ERROR_CODE);
        }
        result.setData(o);
        return result;
    }


    /**
     * 删除单据-只能删除草稿
     * @param id
     * @return
     */
    public ResultData<Object> del(String id) {
        ResultData result = new ResultData();
        GcnSysPage o = gcnSysPageMapper.selectByPrimaryKey(id);
        //o.setIsStop(2);//删除标记
        /*int res = sysPageMapper.updateByPrimaryKeySelective(o);*/
        List<String> childPages = new ArrayList();
        childPages = getChildPage(childPages,o.getPageID());
        childPages.add(o.getPageID());
        System.out.println(childPages);
        int resbatch = gcnSysPageMapper.updateBatch(2,childPages);
        result.setCode(resbatch > 0 ? BaseCode.SUCCESS_CODE : BaseCode.ERROR_CODE);
        return result;
    }

    public List<String> getChildPage(List<String> childPages,String pageID){
        List<Map<String,String>> sysPages = gcnSysPageMapper.queryChildrenInParentID(pageID);
        for (Map<String,String> map : sysPages){
            childPages.add(map.get("pageID"));
            if(childPages.size()>0){
                getChildPage(childPages,map.get("pageID"));
            }
        }
        return childPages;
    }

    public Map getPageList(String pageID) {
        StringBuffer condition = new StringBuffer();
        condition.append(" AND isStop != 2");
        List<GcnSysPage> list = gcnSysPageMapper.getPageList(condition.toString());
        HashMap result = new HashMap();
        result.put("data", list);
        return result;
    }

    /**
     * 获取某个父节点下面的所有子节点
     * @param list
     * @param pid
     * @return
     */
    public static List<GcnSysPage> treeList( List<GcnSysPage> list, String pid){
        for(GcnSysPage p: list){
            //遍历出父id等于参数的id，add进子节点集合
            if(pid.equals( p.getParentID())){
                //递归遍历下一级
                treeList(list, p.getParentID());
                childNodes.add( p);
            }
        }
        return childNodes;
    }

    public Map getEnabledPageList(String type) {
        //String condition = "";
        StringBuffer condition = new StringBuffer();
        if(CommonUtils.isNotEmpty(type) && "1".equals(type)) {
            condition.append(" AND isStop != 2");
        }else{
            condition.append(" AND isStop = 0");
        }
        List<GcnSysPage> list = gcnSysPageMapper.getPageList(condition.toString());
        HashMap result = new HashMap();
        result.put("data", list);
        return result;
    }

    public List<Map<String,String>> getAllAndHasRole(String roleID){
        return gcnSysPageMapper.getAllAndHasRole(roleID);
    }
}
